package com.inlycat.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Properties;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * @author jarvan4dev@163.com
 * @since 2015年8月23日下午6:10:53
 * @category
 
 
 
 
  
 **/
public class SMSUtil {

	public static ObjectNode sendSMS(String mobile, int code) throws IOException {

		Properties prop = new Properties();
		/**
		 * 获取当前项目根目录src
		 */
		String base = SMSUtil.class.getResource("/").getPath();
		InputStream inStream = new FileInputStream(base+"/sms.properties");
		prop.load(inStream);
		String sendUrl = prop.getProperty("url");
		String appkey = prop.getProperty("appkey");
		String appName = prop.getProperty("app_name");
		String tplId = prop.getProperty("tpl_id");

		/**
		 * 将请求数据进行编码
		 */
		String value = URLEncoder.encode(
				"#app#=" + appName + "&#code#=" + code, "UTF-8");

		/**
		 * 拼接请求uri
		 */
		String uri = sendUrl + "?mobile=" + mobile + "&tpl_id=" + tplId
				+ "&tpl_value=" + value + "&key=" + appkey;

		URL url = new URL(uri);
		inStream = url.openStream();
		/*ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		// 将输入流转移到内存输出流中
		while ((len = inStream.read(buffer, 0, buffer.length)) != -1) {
			byteArrayOutputStream.write(buffer, 0, len);
		}
		// 将内存流转换为字符串
		String jsonStr = new String(byteArrayOutputStream.toByteArray());*/
		ObjectMapper mapper = new ObjectMapper();
		ObjectNode objNode = mapper.readValue(inStream, ObjectNode.class);
		System.out.println(objNode.get("reason").asText());
		return objNode;
		
	}

	public static void main(String[] args) throws IOException {
		sendSMS("18651834732", 123416);
	}
}
